package ltd.bugs.cute.channel.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ltd.bugs.cute.cache.CacheClient;
import ltd.bugs.cute.cache.CacheKeyUtil;
import ltd.bugs.cute.cache.callback.GetCallback;
import ltd.bugs.cute.channel.dao.ChannelDAO;
import ltd.bugs.cute.channel.model.Channel;
import ltd.bugs.cute.channel.model.ChannelCondition;

/**
 * 通道的服务
 * 
 * @author zhengzhq
 *
 */
@Service
public class ChannelService {

  @Autowired
  private ChannelDAO channelDAO;
  private static final CacheKeyUtil keyUtil = new CacheKeyUtil(Channel.class);
  public static final String allChannelGroupKey = keyUtil.getGroupKey(".all");

  public Channel get(long id) {
    return CacheClient.get(keyUtil.getRecKey("." + id), new GetCallback<Channel>() {

      @Override
      public String getCacheGroup() {
        return null;
      }

      @Override
      public Channel getObject() {
        return channelDAO.get(id);
      }
    });
  }

  public void update(Channel channel) {
    channelDAO.update(channel);
    CacheClient.remove(keyUtil.getRecKey("." + channel.getId()));
    // 所有的通道列表缓存都失效
    CacheClient.remove(allChannelGroupKey);
  }

  public void delete(long id) {
    channelDAO.delete(id);
    CacheClient.remove(keyUtil.getRecKey("." + id));
    // 所有的通道列表缓存都失效
    CacheClient.remove(allChannelGroupKey);
  }

  public void add(Channel channel) {
    channelDAO.add(channel);
    // 所有的通道列表缓存都失效
    CacheClient.remove(allChannelGroupKey);
  }

  public List<Channel> getChannelList(ChannelCondition condition) {
    return CacheClient.get(
        keyUtil.getRecKey(".type." + condition.getType() + ".status." + condition.getStatus()),
        new GetCallback<List<Channel>>() {

          @Override
          public String getCacheGroup() {
            return allChannelGroupKey;
          }

          @Override
          public List<Channel> getObject() {
            return channelDAO.getChannelList(condition);
          }
        });
  }
}
